import { getCartList, updateCart } from '@/api/cart'
import myAxios from '@/utils/request'
import { Toast } from 'vant'

export default {
  namespaced: true, // 开启命名空间
  state () {
    return {
      cartList: [] // 购物车列表
    }
  },
  mutations: {
    // 添加商品到购物车
    setCartList (state, newList) {
      state.cartList = newList
    },
    // 修改商品选中状态
    addGoodChecked (state, id) {
      const good = state.cartList.find(item => item.goods_id === id)
      good.isChecked = !good.isChecked
    },
    // 全选修改所有商品选中状态
    addAllChecked (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    // 修改商品数量
    updataCartList (state, obj) {
      const { goodsNum, goodsId } = obj
      const good = state.cartList.find(item => item.goods_id === goodsId)
      good.goods_num = goodsNum
    }
  },
  actions: {
    // 获取购物车列表
    async getCartList ({ commit }) {
      // 获取购物车列表
      const result = await getCartList()
      // 添加isChecked字段
      const list = result.data.list
      list.forEach(item => {
        item.isChecked = true
      })
      // 提交到mutations
      commit('setCartList', list)
    },
    // 更新购物车
    async updateCartAsync ({ commit }, obj) {
      try {
        await updateCart(obj)
        // 刷新购物车列表
        commit('updataCartList', obj)
      } catch (error) {
        console.dir(error)
      }
    },
    // 删除购物车
    async deleteCartAsync (content) {
      const list = content.getters.goodsCheckedList
      const ids = list.map(item => item.id)
      await myAxios({
        url: '/cart/clear',
        method: 'POST',
        data: {
          cartIds: ids
        }
      })

      await content.dispatch('getCartList')

      Toast('删除成功')
    }
  },
  getters: {
    // 获取商品总数
    goodsTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 获取选中商品列表
    goodsCheckedList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 获取选中商品总价
    goodsCheckedPriceTotal (state, getters) {
      return getters.goodsCheckedList.reduce((sum, item) => {
        return sum + item.goods_num * item.goods.goods_price_max
      }, 0)
    },
    // 获取是否全选
    setAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
